{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Deep Feature Synthesis\n",
    "\n",
    "Deep Feature Synthesis (DFS) is an automated method for performing feature engineering on relational and temporal data.\n",
    "\n",
    "## Input Data\n",
    "\n",
    "Deep Feature Synthesis requires structured datasets in order to perform feature engineering. To demonstrate the capabilities of DFS, we will use a mock customer transactions dataset.\n"
   ],
   "metadata": {}
  },
  {
   "cell_type": "raw",
   "source": [
    ".. note ::\n",
    "\n",
    "  Before using DFS, it is recommended that you prepare your data as an :class:`EntitySet`.  See :doc:`using_entitysets` to learn how."
   ],
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "import featuretools as ft\n",
    "es = ft.demo.load_mock_customer(return_entityset=True)\n",
    "es"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "Once data is prepared as an `.EntitySet`, we are ready to automatically generate features for a target dataframe - e.g. `customers`.\n",
    "\n",
    "## Running DFS\n",
    "\n",
    "Typically, without automated feature engineering, a data scientist would write code to aggregate data for a customer, and apply different statistical functions resulting in features quantifying the customer's behavior. In this example, an expert might be interested in features such as: *total number of sessions* or *month the customer signed up*.\n",
    "\n",
    "These features can be generated by DFS when we specify the target_dataframe as `customers` and `\"count\"` and `\"month\"` as primitives."
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "feature_matrix, feature_defs = ft.dfs(entityset=es,\n",
    "                                      target_dataframe_name=\"customers\",\n",
    "                                      agg_primitives=[\"count\"],\n",
    "                                      trans_primitives=[\"month\"],\n",
    "                                      max_depth=1)\n",
    "feature_matrix"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "In the example above, `\"count\"` is an **aggregation primitive** because it computes a single value based on many sessions related to one customer. `\"month\"` is called a **transform primitive** because it takes one value for a customer transforms it to another."
   ],
   "metadata": {}
  },
  {
   "cell_type": "raw",
   "source": [
    ".. note ::\n",
    "\n",
    "  Feature primitives are a fundamental component to Featuretools. To learn more read :doc:`primitives`."
   ],
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Creating \"Deep Features\"\n",
    "\n",
    "The name Deep Feature Synthesis comes from the algorithm's ability to stack primitives to generate more complex features. Each time we stack a primitive we increase the \"depth\" of a feature. The `max_depth` parameter controls the maximum depth of the features returned by DFS. Let us try running DFS with `max_depth=2`"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "feature_matrix, feature_defs = ft.dfs(entityset=es,\n",
    "                                      target_dataframe_name=\"customers\",\n",
    "                                      agg_primitives=[\"mean\", \"sum\", \"mode\"],\n",
    "                                      trans_primitives=[\"month\", \"hour\"],\n",
    "                                      max_depth=2)\n",
    "feature_matrix"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "With a depth of 2, a number of features are generated using the supplied primitives. The algorithm to synthesize these definitions is described in this [paper](http://www.jmaxkanter.com/static/papers/DSAA_DSM_2015.pdf). In the returned feature matrix, let us understand one of the depth 2 features"
   ],
   "metadata": {
    "raw_mimetype": "text/markdown"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "feature_matrix[['MEAN(sessions.SUM(transactions.amount))']]"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "For each customer this feature\n",
    "\n",
    "1. calculates the ``sum`` of all transaction amounts per session to get total amount per session,\n",
    "2. then applies the ``mean`` to the total amounts across multiple sessions to identify the *average amount spent per session*\n",
    "\n",
    "We call this feature a \"deep feature\" with a depth of 2.\n",
    "\n",
    "Let's look at another depth 2 feature that calculates for every customer *the most common hour of the day when they start a session*"
   ],
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "feature_matrix[['MODE(sessions.HOUR(session_start))']]"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "For each customer this feature calculates\n",
    "\n",
    "1. The `hour` of the day each of his or her sessions started, then\n",
    "2. uses the statistical function `mode` to identify the most common hour he or she started a session\n",
    "\n",
    "Stacking results in features that are more expressive than individual primitives themselves. This enables the automatic creation of complex patterns for machine learning."
   ],
   "metadata": {}
  },
  {
   "cell_type": "raw",
   "source": [
    ".. note ::\n",
    "    You can graphically visualize the lineage of a feature by calling :func:`featuretools.graph_feature` on it. You can also generate an English description of the feature with :func:`featuretools.describe_feature`. See :doc:`/guides/feature_descriptions` for more details."
   ],
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Changing Target DataFrame\n",
    "\n",
    "DFS is powerful because we can create a feature matrix for any dataframe in our dataset. If we switch our target dataframe to \"sessions\", we can synthesize features for each session instead of each customer. Now, we can use these features to predict the outcome of a session."
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "feature_matrix, feature_defs = ft.dfs(entityset=es,\n",
    "                                      target_dataframe_name=\"sessions\",\n",
    "                                      agg_primitives=[\"mean\", \"sum\", \"mode\"],\n",
    "                                      trans_primitives=[\"month\", \"hour\"],\n",
    "                                      max_depth=2)\n",
    "feature_matrix.head(5)"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "As we can see, DFS will also build deep features based on a parent dataframe, in this case the customer of a particular session. For example, the feature below calculates the mean transaction amount of the customer of the session."
   ],
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "feature_matrix[['customers.MEAN(transactions.amount)']].head(5)"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "raw",
   "source": [
    "Improve feature output\n",
    "~~~~~~~~~~~~~~~~~~~~~~\n",
    "\n",
    "To learn about the parameters to change in DFS read :doc:`/guides/tuning_dfs`.\n",
    "\n",
    "\n",
    ".. here it maybe nice to have a table that shows the number of features generated for AirBnB and other KAGGLE datasets once we have them. We can also give the user access to it."
   ],
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   }
  }
 ],
 "metadata": {
  "celltoolbar": "Raw Cell Format",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}